package org.example.seata.common.security.config.auth.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.example.seata.bs.api.entity.account.AccountAuth;
import org.example.seata.bs.api.service.account.AccountAuthService;
import org.example.seata.common.security.constant.AuthTypeConst;
import org.example.seata.common.security.service.CustomUser;
import org.example.seata.common.security.util.MenuFacUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 支持刷新token
 * 检验token
 *
 * @author hzq
 * @date 2021/12/6 14:15
 */
@Component
@AllArgsConstructor
public class UnionIdAuthHandler implements AuthHandler {

    private final AccountAuthService accountAuthService;

    public UserDetails handler(String principal, String credentials, Map<String, String> parameters) {

        String authType = parameters.get(AuthTypeConst.AUTH_TYPE);

        if (StrUtil.isBlank(authType)) {
            throw new UnsupportedGrantTypeException("Unsupported auth type: " + authType);
        }

        LambdaQueryWrapper<AccountAuth> wrapper = Wrappers.<AccountAuth>lambdaQuery()
                .eq(AccountAuth::getAuthType, authType)
                .eq(AccountAuth::getUnionId, principal);

        AccountAuth auth = accountAuthService.getOne(wrapper);

        // 检验认证信息
        checkAuth(auth);

        List<GrantedAuthority> userMenu = MenuFacUtil.getUserMenu(auth);

        return new CustomUser(auth, userMenu);
    }

    public String getHandlerType() {
        return AuthTypeConst.UNION_ID;
    }
}
